<template>
  <div class="marketPushDown" @click.stop="aotuTab=false">
    <div>
      <el-button size="mini" type="primary" @click="preservation">{{ $t('btn.save') }}</el-button>
    </div>
    <el-tabs v-model="activeName" class="tabs">
      <el-tab-pane :label="$t('market.info')" name="basic">
        <el-form
          ref="jcForm"
          :model="optionValue"
          size="mini"
          label-width="80px"
        >
          <el-form-item :label="$t('market.state')">
            <el-tag>{{ optionValue.fdocumentStatus }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.billType')">
            <el-select v-model="optionValue.fbilltypeid" @change="queryProval">
              <el-option
                v-for="option in billType"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="采购组织">-->
          <!--            <el-select v-model.trim="optionValue.fpurchaseorgid" @change="saleHeadel">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item :label="$t('market.billNo')">
            <el-input v-model="optionValue.fbillno" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.applicant')">
            <el-autocomplete
              v-model.trim="optionValue.fapplicant"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch19"
              size="mini"
              @focus="handleApplicant"
              @select="selectApply"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="userVisiblit = true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.applyDate')">
            <el-date-picker
              v-model="optionValue.fdate"
              value-format="yyyy-MM-dd"
              size="mini"
              type="date"
              class="input-width"
            />
          </el-form-item>
          <el-form-item :label="$t('market.usedepid')">
            <el-autocomplete
              v-model.trim="optionValue.fdeptName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch8"
              @focus="getBasicUnit('SX_V_WORKSHOP')"
              @select="selUnit"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="unitVisabled=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.note')" style="width: 33.3%;">
            <el-input v-model="optionValue.fnote" style="width: 100%" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.fince')" name="first">
        <el-form
          ref="jcForm"
          :model="optionValue"
          size="mini"
          label-width="80px"
        >
          <!--          <el-form-item label="结算组织">-->
          <!--            <el-select v-model.trim="optionValue.fsettleorgid">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item :label="$t('market.currency2')" prop="fsettleCurrId">
            <el-autocomplete
              v-model.trim="optionValue.fsettleCurr"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch5"
              size="mini"
              @focus="queryTBdCurrency"
              @select="currencyData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="currencyVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.exchangeType')" prop="fexchangetypeid">
            <el-autocomplete
              v-model.trim="optionValue.fexchangeType"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch20"
              size="mini"
              @focus="queryRateType"
              @select="ratesData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="rateTypeVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.exchangeRate')">
            <el-input v-model="optionValue.fexchangeRate" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.localCurr')">
            <el-input v-model="optionValue.flocalCurr" disabled />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div style="margin-bottom: 5px;margin-top: 10px;">
      <el-button size="mini" @click="newRow">{{ $t('btn.newHang') }}<!--新增行--></el-button>
      <el-button size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
      <el-button size="mini" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
    </div>
    <div>
      <jc-table
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        serial
        @rowClick="rowClick"
        @cellClick="cellClick"
      >
        <el-table-column
          :label="$t('market.fmaterial')"
          prop="fnumber"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-input
              v-model.trim="scope.row.fnumber"
              size="mini"
              @input="getAtuo(scope.$index, scope.row.fnumber)"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="handleMateriel(scope.$index)"
              />
            </el-input>
            <div v-if="aotuTab && materielIndex === scope.$index" :class="materielIndex<7 ? 'tabPosit': 'tabPosit1'">
              <number-code :fnumber="fnumber" @material="materialData" />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('shop.fname2')"
          prop="fname"
          align="center"
        />
        <el-table-column :label="$t('shop.specifica')" prop="fspecificaTion" align="center" show-overflow-tooltip />
        <el-table-column :label="$t('market.fmodel')" prop="fmodel" align="center" />
        <el-table-column :label="$t('market.funit')" prop="funit" align="center" />
        <el-table-column :label="$t('market.appQty')" prop="freqqty" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-model.number="scope.row.freqqty"
              :min="0"
              size="mini"
              @change="fqeyhendel(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('market.approveqty')" prop="fapproveqty" align="center" />
        <el-table-column :label="$t('market.arrivalDate')" prop="farrivalDate" align="center">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.farrivalDate"
              type="date"
              value-format="yyyy-MM-dd"
              size="mini"
              style="width: 163px"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('market.stock2')" prop="fstock" align="center">
          <template slot-scope="scope">
            <el-autocomplete
              v-model.trim="scope.row.fstock"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch21"
              size="mini"
              @focus="handleWarehouse(scope.$index)"
              @select="selectData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="handleCK(scope.$index)"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </template>
        </el-table-column>
        <el-table-column :label="$t('market.paezText1')" prop="fpaezText" align="center">
          <template slot-scope="scope">
            <el-input v-model.trim="scope.row.fpaezText" size="mini" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('market.productmodel')" prop="fproductmodel" align="center">
          <template slot-scope="scope">
            <el-input v-model.trim="scope.row.fproductmodel" size="mini" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="库存组织" align="center">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-select v-model="scope.row.fstockorgid">-->
        <!--              <el-option-->
        <!--                v-for="option in teamList"-->
        <!--                :key="option.fid"-->
        <!--                :label="option.fname"-->
        <!--                :value="option.fid"-->
        <!--              />-->
        <!--            </el-select>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          :label="$t('market.chargeunit1')"
          prop="fpriceunit"
          align="center"
          width="80"
        />
        <el-table-column
          :label="$t('market.chargeQty1')"
          prop="fbaseunitqty"
          align="center"
          width="80"
        >
          <template slot-scope="scope">
            <el-input-number
              v-model.number="scope.row.fbaseunitqty"
              :min="0"
              size="mini"
              @change="baseunitChange(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('market.note')" prop="fentrynote" align="center" width="120">
          <template slot-scope="scope">
            <el-autocomplete v-model.trim="scope.row.fentrynote" />
          </template>
        </el-table-column>
      </jc-table>
    </div>
    <!--汇率类型-->
    <ratesType v-if="rateTypeVisiblit" @rates="ratesData" />
    <!--币别-->
    <currency v-if="currencyVisiblit" @currency="currencyData" />
    <!--    物料弹窗-->
    <material v-if="isMateria" :fispur-chase="fispurChase" @material="materialData" />
    <!--申请人-->
    <user v-if="userVisiblit" @supplier="selectApply" />
    <!--  数据字典弹窗  -->
    <unit v-if="unitVisabled" msg="SX_V_WORKSHOP" @unit="selUnit" />
    <!-- 仓库 -->
    <selectCK
      v-if="seleceVisiblit"
      @client="selectData"
    />
  </div>
</template>
<script>
import {
  basicprocurement,
  insertRequistion, procurementbasic
} from '@/api/purchaseManagement/apply'
import ratesType from '@/views/basic/currencyRates/rates/components/rateType'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import { queryFxxchange, queryOrgDetail, queryRate, queryViewItem } from '@/api/marketManage/marketOrder'
import bility from '@/mixin/Operability'

export default {
  name: 'CreateApply',
  components: {
    unit: () => import('@/views/basic/createMateriel2/components/unit'),
    selectCK: () => import('@/views/production/collect/components/seleceCK'),
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    material: () => import('@/views/market/marketManage/createMarkerOrder/components/material'),
    ratesType,
    user: () => import('@/views/basic/users/userslist/component/user'),
    numberCode: () => import('@/components/NumberCode')
  },
  mixins: [autocomplete, bility],
  data() {
    return {
      unitVisabled: false,
      activeName: 'basic', // 基本信息
      activeName1: 'detailed', // 明细信息
      fispurChase: '1', // 允许采购
      optionValue: {
        fapplicant: '',
        fapplicantId: '',
        fbillno: '',
        fbilltypeid: 147,
        fsettleCurr: '人民币',
        fsettleCurrId: '1',
        fnote: '',
        fexchangetypeid: 5,
        fexchangeType: '每月汇率',
        fdate: new Date(),
        fdocumentStatus: '创建'
      },
      tableData: [
        {
          fnumber: '',
          fstockorgid: 1,
          funit: '',
          fname: '',
          fspecificaTion: '',
          fmodel: '',
          freqqty: 0,
          fapproveqty: 0,
          fsupplier: '',
          fstock: '',
          fpriceunit: '',
          farrivalDate: new Date()
        }
      ],
      tableHeight: 'calc(100vh - 290px)',
      tableHeader: [],
      billType: [], // 单据类型
      isMateria: false, // 物料弹窗
      currencyVisiblit: false, // 币别
      materielIndex: 0, // 物料
      rateTypeVisiblit: false, // 汇率类型
      seleceVisiblit: false, // 仓库
      userVisiblit: false, // 供应商
      aotuTab: false,
      fnumber: ''
    }
  },
  watch: {
    'optionValue.fpurchaseorgid': {
      handler(val) {
        this.tableData.map(res => {
          res.fstockorgid = val
        })
      }
    }
  },
  created() {
    this.getForm()
    this.queryProval()
  },
  methods: {
    // 监听单据类型
    queryProval() {
      const DATA = {
        fid: this.optionValue.fbilltypeid || 0,
        viewName: 'SX_PUR_REQUISITION'
      }
      queryFxxchange(DATA).then(res => {
        if (res.code === 0) {
          this.optionValue = {
            ...this.optionValue,
            fpurchaseorgid: res.data.fsaleorgid,
            ...res.data
          }
        }
      })
    },
    // 监听组织
    saleHeadel(forgids) {
      this.optionValue.fsettleorgid = this.optionValue.fsaleorgid
      queryOrgDetail({ forgids }).then(res => {
        if (res.code === 0) {
          this.optionValue = {
            ...this.optionValue,
            ...res.data
          }
        }
      })
    },
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.materielIndex = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber = fnumber
      }, 600)
    },
    // 保存
    preservation() {
      if (!this.optionValue.fapplicantId) {
        this.$message({ showClose: true, message: '请选择申请人', type: 'warning' })
        return
      }
      const tableData = this.tableData[this.materielIndex]
      if (!tableData.fmaterialId) {
        this.$message.warning('请选择物料编码！')
        return
      } else if (tableData.freqqty <= 0) {
        this.$message.warning('申请数量不能小于0！')
        return
      }
      const parameter = {
        ...this.optionValue,
        fdocumentStatus: 'A',
        details: this.tableData
      }
      insertRequistion(parameter).then(res => {
        const { code, data, message } = res
        if (code !== 0) {
          this.$message({ showClose: true, message: message, type: 'warning' })
          return
        }
        this.$message({ showClose: true, message: message, type: 'success' })
        // 关闭当前页面
        this.$store.dispatch('tagsView/guanbi', this.$route)
        this.$router.push({ path: `/editApply/${data}` })
        this.optionValue.fbillNo = data
      })
    },
    // 物料编码
    handleMateriel(index) {
      this.materielIndex = index
      this.isMateria = true
    },
    // 获取物料
    materialData(item) {
      const {
        fnumber,
        fpurchaseUnit,
        fspecificaTion,
        fmodel,
        fpurchaseUnitId,
        fname,
        fdescripTion,
        fmaterialId,
        fstock,
        fstockId,
        funitId,
        fpurchasepriceUnit,
        fpurchasepriceUnitId
      } = item
      const tableData = this.tableData[this.materielIndex]
      tableData.fnumber = fnumber
      tableData.funit = fpurchaseUnit
      tableData.funitId = fpurchaseUnitId
      tableData.fbaseunitid = funitId
      tableData.fspecificaTion = fspecificaTion
      tableData.fmodel = fmodel
      tableData.fname = fname
      tableData.fstock = fstock
      tableData.fstockId = fstockId
      tableData.fdescripTion = fdescripTion
      tableData.fpriceunit = fpurchasepriceUnit
      tableData.fpriceunitid = fpurchasepriceUnitId
      tableData.fmaterialId = fmaterialId // 用来保证用户是否选择了物料编码(临时参数)
      this.isMateria = false
    },
    // 监听基本数量
    baseunitChange(index) {
      const { fbaseunitid, freqqty, fbaseunitqty, fmaterialId, fnumber, funitId } = this.tableData[index]
      const DATA = {
        fbaseunitid, fbaseunitqty, fmaterialId, fnumber, funitId, freqqty
      }
      basicprocurement(DATA).then(res => {
        if (res.code === 0) {
          const item = this.tableData[index]
          item.freqqty = res.data.priceunitqty
          item.fapproveqty = res.data.priceunitqty
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 批准数量
    fqeyhendel(index) {
      const { fbaseunitid, freqqty, fbaseunitqty, fmaterialId, fnumber, funitId, fbaseqty } = this.tableData[index]
      this.tableData[index].fneedqty = freqqty + fbaseqty
      const DATA = {
        fbaseunitid, fbaseunitqty, fmaterialId, fnumber, funitId, freqqty
      }
      procurementbasic(DATA).then(res => {
        if (res.code === 0) {
          const item = this.tableData[index]
          item.fapproveqty = item.freqqty
          item.fbaseunitqty = res.data.baseunitqty
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 币别
    currencyData(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.optionValue.fsettleCurr = item.fsettleCurrIdName || item.fname
        this.optionValue.fsettleCurrId = item.fsettleCurrId || item.fcurrencyId
        this.querySalerRate()
      }
      this.currencyVisiblit = false
    },
    // 查询销售订单汇率
    async querySalerRate() {
      const DATA = {
        tocurrId: this.optionValue.flocalCurrId, // 本位币
        fromcurrId: this.optionValue.fsettleCurrId, // 结算币别
        queryDate: this.optionValue.fdate
      }
      const { data: RES, code, message } = await queryRate(DATA)
      if (code === 0) {
        this.optionValue.fexchangeRate = RES.exchangeRate
        this.optionValue.fexchangeType = RES.exchangeTypeName
        this.optionValue.fexchangeTypeId = RES.exchangeTypeId
      } else {
        this.optionValue.fexchangeRate = ''
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 仓库
    handleCK(index) {
      this.materielIndex = index
      this.seleceVisiblit = true
    },
    // 获取仓库数据
    selectData(ev) {
      if (ev.fstockId) {
        this.tableData[this.materielIndex].fstockId = ev.fstockId
        this.tableData[this.materielIndex].fstock = ev.fname
      }
      this.seleceVisiblit = false
    },
    // 汇率类型
    ratesData(ev) {
      if (ev.fid) {
        this.optionValue.fexchangetypeid = ev.fgroupId
        this.optionValue.fexchangeType = ev.fgroupName
      }
      this.rateTypeVisiblit = false
    },
    // 申请人双击
    selectApply(item) {
      if (item.fuserId) {
        this.optionValue.fapplicant = item.fname
        this.optionValue.fapplicantId = item.fuserId
      }
      this.userVisiblit = false
    },
    // 数据字典选中
    selUnit(ev) {
      if (ev.fid) { // 生产部门
        this.optionValue.fusedept = ev.fid
        this.optionValue.fdeptName = ev.fname
      }
      this.unitVisabled = false
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增行
    newRow() {
      const DATA = {
        fentrynote: '',
        fpaezText: '',
        fproductmodel: '',
        fnumber: '',
        funit: '',
        fname: '',
        fspecificaTion: '',
        fmodel: '',
        freqqty: 0,
        fapproveqty: 0,
        fsupplier: '',
        fstock: '',
        fpriceunit: '',
        farrivalDate: new Date()
      }
      this.tableData.push(DATA)
    },
    // 删除行
    delHang() {
      this.tableData.splice(this.indexSelf, 1)
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.tableData[this.subscript][this.property]
      const fstock = this.tableData[this.subscript].fstockId
      this.tableData.map((res, index) => {
        if (index >= this.subscript) {
          if (this.property === 'freqqty') {
            res.fapproveqty = item
          } else if (this.property === 'fstock') {
            res.fstockId = fstock
          }
          res[this.property] = item
        }
      })
    },
    // 数据初始化
    async getForm() {
      // 单据类型
      const { data: billTypeList } = await queryViewItem(
        { viewName: 'SX_PUR_REQUISITION' })
      this.billType = billTypeList.list.map(item => {
        const { fid: value, fname: label } = item
        return { label, value }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.marketPushDown {
  @include listBom;
  padding: 10px;
  background: #fff;
  .tabs {
    height: 100px;
  }
  .tabPosit {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: 3.5vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 99999!important;
  }
  .tabPosit1 {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: -25.69vh;
    left:0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 35px;
      width: 275px;
      min-width: 246px;
      margin-bottom: 5px;

      .el-date-editor.el-input {
        width: 100% !important;
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
